package cn.tedu.csmall.product.config;

import cn.tedu.csmall.product.filter.JwtAuthorizationFilter;
import cn.tedu.csmall.product.web.JsonResult;
import cn.tedu.csmall.product.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Spring Security的配置类，
 * 重写configure(HttpSecurity http)方法后，将取消框架自带的一些功能特性
 * 1. 访问url不再需要强制登陆
 * 2. 登录，登出的页面不再显示
 */

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    JwtAuthorizationFilter jwtAuthorizationFilter;





    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 处理“需要通过认证，但是实际上未通过认证就发起的请求”导致的错误
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                String message = "未检测到登录，请登录！（在开发阶段，看到此提示时，请检查客户端是否携带了JWT向服务器端发起请求）";
                JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERR_UNAUTHORIZED, message);
                response.setContentType("application/json; charset=utf-8");
                PrintWriter printWriter = response.getWriter();
                printWriter.println(JSON.toJSONString(jsonResult));
                printWriter.close();
            }
        });

//        白名单url,即忽略认证
        String[] url = {
                "/doc.html",
                "/**/*.js",
                "/**/*.css",
                "swagger-resources",
                "/v2/api-docs",
        };

        http.cors();

//        调用此方法后，Security框架将支持POST请求[默认支持GET请求]
        http.csrf().disable();
//        调用此方法，表示启用登录表单和登出表单，若为调用则没有这两个页面显示
//        http.formLogin();
//        配置URL的访问控制
        http.authorizeRequests() //
                .mvcMatchers(url) //匹配某些url地址
                .permitAll()     //直接许可，不需要认证登录
                .anyRequest()    //指定任意请求
                .authenticated(); //以上配置的请求地址都需要认证通过

        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);
    }

}
